package com.hsmpay.yl8583.service;

import com.hsmpay.base.PayBaseService;
import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.qian4.pojo.BalanceResult;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.pojo.RevocationResult;
import com.hsmpay.qian4.pojo.send.ICCardParam;
import com.hsmpay.utils.StringBUtils;
import com.hsmpay.utils.WriteFile;
import com.hsmpay.utils.ZhongLanResCode;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.Map;

/**
 * 卡连卡
 */
public class KaYinKaService extends PayBaseService {

    static Logger log = Logger.getLogger(KaYinKaService.class);
    public KaYinKaSocketToBoss st = null;

    public String merchantId = "600000000000001";//商户号
    public String terminalId = "11111111";//终端号
    public String batch = "000001";//
    static WriteFile wf = new WriteFile("ds_kayinka");

    public KaYinKaService(String merchantId, String terminalId, String batch, String MasterKey, String PinKey, String MacKey, String trkKey, Map<String,String> config){
        this.merchantId = merchantId;
        this.terminalId = terminalId;
        this.batch = batch;
        st = new KaYinKaSocketToBoss(merchantId,terminalId,batch,MasterKey,PinKey,MacKey,trkKey,config);
    }

    /**
     * 签到
     * @param bankOrderNum
     * @return
     * @throws Exception
     */
    public String login(String bankOrderNum)throws Exception{//批次号 使用的是终端
        String result = "-1_ _ _ _ _ ";
        if(!isFormal()){
            log.debug("测试环境");
            result = "0_00_000001_3D311049CA7FE49AC7206997E810C562_8F8ABD54D90DD3D20000000000000000";
        }else{
            String ter = st.Login0800(bankOrderNum);
            String[] terA = ter.split("_");
            if(!"-1".equals(terA[0])){
                if("00".equals(terA[1])){
                    result = ter;
                }else{
                    result = "0_"+terA[1]+" _ _ _ _ ";
                }
            }
        }
        log.debug("中岚签到返回："+result);
        return result;
    }

    /**
     * 有效期 返回4位  5F24的值前4个字符  有效期  5F24是：YYMMDD
     * @return
     */
    private static String getIcc14(ICCardParam iccParam){
        if(null == iccParam || StringUtils.isEmpty(iccParam.getP_5f24())) return "";
        String r = iccParam.getP_5f24().substring(0, 4);
        return r;
    }
    /**
     * IC卡序列 5F34的值,5F34的值不足3位前补0
     * @return
     */
    private String getIcc23(ICCardParam iccParam){
        if(null == iccParam || StringUtils.isEmpty(iccParam.getP_5f34())) return "";
        String r = iccParam.getP_5f34();
        if(r.length() <= 3){
            r = StringBUtils.supplyAll(r, 3);
        }else if (r.length() > 3 && r.contains("1")){
            r = "001";
        }else{
            r = "000";
        }
        return r;
    }
    /**
     * 55域
     * @param iccParam
     * @return
     */
    private String getIcc55(ICCardParam iccParam){
        if(null == iccParam || StringUtils.isEmpty(iccParam.getIcCardYu())) return "";
        String bit55Str = iccParam.getBit55();
        log.debug("IC卡 bit55："+bit55Str);
        return bit55Str;
    }

    /**
     * 消费
     * @param send
     * @param
     * @return
     * @throws Exception
     */
    public PurchaseResult billPayment(Qian4SendLog send)throws Exception{
        PurchaseResult rs = new PurchaseResult();
        String money = StringBUtils.supplyAll(send.getTransAmt(), 12);
        String resStr = "";
        if(!isFormal()){
            log.debug("测试环境");
            resStr = "0_6217991000008070299_000000002000_100808_170407_0309_2411_606917884786_000000_00";
        }else{
            send.setTrack3Data("");//####屏蔽3磁道
            String bit14 = getIcc14(send.getIccParam());
            String bit23 = getIcc23(send.getIccParam());
            String bit55 = getIcc55(send.getIccParam());
            resStr = st.BillPayment(send.getTrack2Data(), send.getTrack3Data(), send.getPin(), money , send.getAccountNumber(),send.getBankOrderNum(),bit23,bit55,bit14);
        }
        log.debug("卡银卡消费响应："+resStr);
        String[] resArray = resStr.split("_");
        if("-1".equals(resArray[0])){
            rs.setStatus(0);
            rs.setReqCode("9999");
            rs.setReqMsg("由于网络原因，银联接口异常，请稍候再试！");
        }else{
            rs.setStatus(1);
            String reqCode =  StringBUtils.supplyAll(resArray[resArray.length-1], 4);
            rs.setReqCode(reqCode);
            rs.setAccountNumber(resArray[1]);
            rs.setBatchId(send.getBatchId());//批次号
            rs.setBankOrderNum(resArray[3]);//流水号
            rs.setBankTransTime(resArray[4]);//交易时间
            rs.setBankTransDate(resArray[5]);//交易日期
            rs.setExpireDate(resArray[6]);//有效期
            rs.setBankRef(resArray[7]);//参考号 37
            rs.setAuthorizationCode(resArray[8]);//授权号 38
            if("0000".equals(reqCode)){
                rs.setReqMsg("收款成功");
            }else{
                log.debug("------------"+resArray[1]+"------------");
                rs.setReqMsg( null == ZhongLanResCode.getZhongLanCode(resArray[resArray.length-1]) ? "交易失败！" : "交易失败-"+ZhongLanResCode.getZhongLanCode(resArray[resArray.length-1]));
            }
        }
        return rs;
    }
    /**
     * 冲正接口
     * @param send
     * @param
     * @return
     * @throws Exception
     */
    public RevocationResult unBillPayment(Qian4SendLog send)throws Exception{

        RevocationResult rr = new RevocationResult();
        String money = StringBUtils.supplyAll(send.getTransAmt(), 12);
        String authorizationCode = send.getAuthorizationCode();
        if(null == authorizationCode) authorizationCode = "";

        String resStr = "";
        if(!isFormal()){
            log.debug("测试环境");
            resStr = "0_ _000000000001_100011_ _ _ _000002350153_151878_00_ _ ";
        }else{
            send.setTrack3Data("");//####屏蔽3磁道
            String bit14 = getIcc14(send.getIccParam());
            String bit23 = getIcc23(send.getIccParam());
            String bit55 = getIcc55(send.getIccParam());
            resStr = st.unBillPayment(money,send.getAccountNumber(),send.getBankOrderNum(),send.getResponseCode(),authorizationCode,bit23,bit55,bit14);

        }
        log.debug("卡银卡冲正接口响应："+resStr);
        String[] resArray = resStr.split("_");

        if("-1".equals(resArray[0])){
            rr.setStatus(0);
            rr.setReqCode("9999");
            rr.setReqMsg("由于网络原因，银联接口异常，请稍候再试！");
        }else{
            rr.setStatus(1);
            String reqCode =  StringBUtils.supplyAll(resArray[resArray.length-2], 4);
            rr.setReqCode(reqCode);
            rr.setAccountNumber(resArray[1]);
            rr.setBankOrderNum(resArray[3]);
            rr.setBankTransTime(resArray[4]);
            rr.setBankTransDate(resArray[5]);
            rr.setExpireDate(resArray[6]);
            rr.setBankRef(resArray[7]);
            rr.setAuthorizationCode(resArray[8]);
            if("0000".equals(reqCode)){
                rr.setReqMsg("冲正成功");
            }else{
                rr.setReqMsg( null == ZhongLanResCode.getZhongLanCode(resArray[resArray.length-3]) ? "冲正失败！" : "冲正失败-"+ZhongLanResCode.getZhongLanCode(resArray[resArray.length-3]));
            }
        }
        return rr;
    }

}
